const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  try {
    switch (event.action) {
      case 'register':
        return await register(event.phone, event.password, wxContext.OPENID)
        
      case 'login':
        return await login(event.phone, event.password)
        
      default:
        return {
          success: false,
          message: '未知操作类型'
        }
    }
  } catch (error) {
    console.error('认证错误:', error)
    return {
      success: false,
      message: '操作失败，请重试',
      error: error.message
    }
  }
}

// 注册函数
async function register(phone, password, openid) {
  // 检查手机号是否已注册
  const userCount = await db.collection('users')
    .where({
      phone: phone
    })
    .count()
  
  if (userCount.total > 0) {
    return {
      success: false,
      message: '该手机号已注册'
    }
  }
  
  // 存储用户信息到云数据库
  await db.collection('users').add({
    data: {
      phone: phone,
      password: password,
      createTime: db.serverDate(),
      _openid: openid
    }
  })
  
  // 获取完整用户信息
  const userRes = await db.collection('users')
    .where({
      phone: phone
    })
    .get()
  
  return {
    success: true,
    user: userRes.data[0]
  }
}

// 登录函数
async function login(phone, password) {
  // 查询用户
  const userRes = await db.collection('users')
    .where({
      phone: phone,
      password: password
    })
    .get()
  
  if (userRes.data && userRes.data.length > 0) {
    return {
      success: true,
      user: userRes.data[0]
    }
  } else {
    return {
      success: false,
      message: '账号或密码错误'
    }
  }
}